package com.bjqh.edu.UI.Fragment;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.util.DialogUtils;
import com.bjqh.edu.Base.AppConstants;
import com.bjqh.edu.Base.GlideRoundTransform;
import com.bjqh.edu.Bean.Index;
import com.bjqh.edu.Bean.UpdateApp;
import com.bjqh.edu.Bean.User;
import com.bjqh.edu.R;
import com.bjqh.edu.UI.Activity.Index.FreeReservationActivity;
import com.bjqh.edu.UI.Activity.Index.HeadlinesActivity;
import com.bjqh.edu.UI.Activity.Index.WebViewAcitviy;
import com.bjqh.edu.UI.Activity.Login.LoginActivity;
import com.bjqh.edu.UI.Utils.UpdateManager;
import com.bjqh.edu.UI.dialog.ConfirmDialog;
import com.bjqh.edu.UI.dialog.LoadDialog;
import com.bjqh.edu.adapter.IndexMenuAdapter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.ta.utdid2.android.utils.StringUtils;
import com.ta.utdid2.android.utils.SystemUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGABanner;
import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by Administrator on 2017/9/6.
 */

public class MainFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    public View mViewRoot;
    Unbinder unbinder;
    @BindView(R.id.banner)
    BGABanner banner;
    @BindView(R.id.gv_menu)
    GridView gvMenu;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_top_tilte)
    RelativeLayout rlTopTilte;
    @BindView(R.id.iv_mf)
    ImageView ivMf;
    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.iv_dh)
    ImageView ivDh;


    public List<Index.MenuBean> menuBeen;
    public List<Index.BannerBean> bannerBeen;
    public List<Index.TeacherBeanX> teacherBeanXes;
    public Index.HeadlinesBean headlinesBean;
    public Index.OrderBean orderBean;
    @BindView(R.id.Banner2)
    BGABanner Banner2;
    @BindView(R.id.tv_new)
    TextView tvNew;
    @BindView(R.id.ll_headslines)
    LinearLayout llHeadslines;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    boolean select = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //判断为空，为空就去加载布局，onCreateView在界面切换的时候会被多次调用,防止界面跳转回来的时候显示空白
        if (mViewRoot == null) {
            mViewRoot = inflater.inflate(R.layout.fragment_main, null);
            unbinder = ButterKnife.bind(this, mViewRoot);
        }
        unbinder = ButterKnife.bind(this, mViewRoot);
        //  int width = getContext().getResources().getDisplayMetrics().widthPixels;

        int height = getContext().getResources().getDisplayMetrics().heightPixels;
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) banner.getLayoutParams();
        //获取当前控件的布局对象
        params.height = height / 4;//设置当前控件布局的高度
        banner.setLayoutParams(params);//将设置好的布局参数应用到控件中

        FrameLayout.LayoutParams params2 = (FrameLayout.LayoutParams) Banner2.getLayoutParams();
        //获取当前控件的布局对象
        params2.height = height / 4;//设置当前控件布局的高度
        Banner2.setLayoutParams(params2);//将设置好的布局参数应用到控件中

        LinearLayout.LayoutParams params3 = (LinearLayout.LayoutParams) ivMf.getLayoutParams();
//获取当前控件的布局对象
        params3.height = height / 6;//设置当前控件布局的高度
        ivMf.setLayoutParams(params3);//将设置好的布局参数应用到控件中


        LoadDialog.initDialog(getActivity(), "正在登陆...");
        tvTitle.setText("千禾学堂");
        tvNew.setSelected(true);
        swipeLayout.setColorSchemeResources(R.color.grean);
        swipeLayout.setOnRefreshListener(this);
        OkGo.post(AppConstants.BASE_URL + "sys/ispay.shtml")
                .tag(this)
                .cacheKey("cacheKey")
                .cacheMode(CacheMode.DEFAULT)
                .params("flag", 2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("版本更新", s);
                        Gson gson = new Gson();
                        UpdateApp updateApp = gson.fromJson(s, UpdateApp.class);
                        if (updateApp != null) {
                            if (updateApp.getMsg().equals("success")) {
                                if (updateApp.getData().getVersionCode() > AppConstants.getVersionCode(getActivity())) {

                                    if (updateApp.getData().getStatus() == 0) {
                                        select = true;
                                    }
                                    if (updateApp.getData().getStatus() == 1) {
                                        select = false;
                                    }
                                    /*OkGo.get(AppConstants.BASE_URL+"sys/appDownload.shtml")//
                                            .tag(this)//
                                            .params("id",updateApp.getData().getId())
                                            .execute(new FileCallback(getSDPath()+"/app.apk") {  //文件下载时，需要指定下载的文件目录和文件名
                                                @Override
                                                public void onSuccess(File file, Call call, Response response) {
                                                    // file 即为文件数据，文件保存在指定目录
                                                    if (!file.exists()) {
                                                        return;
                                                    }
                                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
                                                    getActivity().startActivity(intent);
                                                }

                                                @Override
                                                public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                                                    //这里回调下载进度(该回调在主线程,可以直接更新ui)
                                                    System.out.print(progress+"");
                                                }
                                            });*/


                                    UpdateManager updateManager = new UpdateManager(getActivity(), updateApp.getData().getVersionName(), AppConstants.getVerName(getActivity()), select, AppConstants.BASE_URL + "sys/appDownload.shtml?id=", updateApp.getData().getId() + "");
                                    updateManager.showNoticeDialog();
//
//
//                                    updateApp.getData().getId();


                                }
                            }

                        }


                        //

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        Toast.makeText(getActivity(), "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                        LoadDialog.closeDialog();
                    }
                });


        ivMf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("url", AppConstants.H5_URL + "reg.html");
                intent.setClass(getActivity(), FreeReservationActivity.class);
                getActivity().startActivity(intent);
            }
        });
        ivDh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //  ConfirmDialog confirmDialog=  new ConfirmDialog(getActivity(),"提示","小主，您要给4006326977打电话吗？？",true);
                AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(getActivity()).
                                setTitle("小主，您要给4006326977打电话吗？？")
                                .setPositiveButton("确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4006326977"));
                                                startActivity(intent);

                                            }
                                        });
                normalDialog.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
                // 显示
                normalDialog.show();

            }
        });
        banner.setAutoPlayAble(true);

        banner.setDelegate(new BGABanner.Delegate<RelativeLayout, Index.BannerBean>() {
            @Override
            public void onBannerItemClick(BGABanner banner, RelativeLayout itemView, Index.BannerBean model, int position) {
                // Toast.makeText(banner.getContext(), "点击了" + position, Toast.LENGTH_SHORT).show();
                if (!TextUtils.isEmpty(model.getUrl())) {
                    Intent intent = new Intent();
                    intent.putExtra("url", model.getUrl());
                    intent.setClass(getActivity(), WebViewAcitviy.class);
                    getActivity().startActivity(intent);
                }

            }
        });


        llHeadslines.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HeadlinesActivity.class));
            }
        });
        getValue();


        return mViewRoot;
    }

    public void getValue() {
        LoadDialog.initDialog(getActivity(), "加载中");
        OkGo.post(AppConstants.BASE_URL + "/admin/menuicon/index.shtml")
                .tag(this)
                .cacheKey("cacheKey")
                .cacheMode(CacheMode.DEFAULT)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        //  Toast.makeText(getActivity(), "请求成功" + s, Toast.LENGTH_SHORT).show();
                        Log.i("index+++++++", s);
                        LoadDialog.closeDialog();
                        swipeLayout.setRefreshing(false);
                        Gson gson = new Gson();
                        Index index = gson.fromJson(s, Index.class);
                        menuBeen = index.getMenu();
                        bannerBeen = index.getBanner();
                        teacherBeanXes = index.getTeacher();
                        gvMenu.setNumColumns(4);
                        Log.e("teacher", teacherBeanXes.size() + "");
                        gvMenu.setAdapter(new IndexMenuAdapter(getContext(), menuBeen));
                        banner.setData(R.layout.item_banner, bannerBeen, null);
                        banner.setAdapter(new BGABanner.Adapter<RelativeLayout, Index.BannerBean>() {
                            @Override
                            public void fillBannerItem(BGABanner banner, RelativeLayout itemView, Index.BannerBean model, int position) {
                                ImageView img = (ImageView) itemView.findViewById(R.id.img);
                                TextView content = (TextView) itemView.findViewById(R.id.content);
                                TextView title = (TextView) itemView.findViewById(R.id.title);
                                LinearLayout linearLayout = (LinearLayout) itemView.findViewById(R.id.ll);
                                Glide.with(getActivity()).load(AppConstants.IMG_URL + model.getImg()).diskCacheStrategy(DiskCacheStrategy.ALL
                                ).error(R.mipmap.ls).into(img);
                                if (!StringUtils.isEmpty(model.getName())) {
                                    String[] coArray = model.getName().split(",");
                                    title.setText(coArray[0]);
                                    if (coArray.length >= 2)
                                        content.setText(coArray[1]);
                                } else {
                                    linearLayout.setVisibility(View.GONE);
                                }


                            }
                        });

                        Banner2.setData(R.layout.item_res_teahcer, teacherBeanXes, null);

                        Banner2.setAdapter(new BGABanner.Adapter<RelativeLayout, Index.TeacherBeanX>() {
                            @Override
                            public void fillBannerItem(BGABanner banner, RelativeLayout itemView, Index.TeacherBeanX model, int position) {
                                ImageView img = (ImageView) itemView.findViewById(R.id.img);
                                TextView name = (TextView) itemView.findViewById(R.id.name);
                                TextView school = (TextView) itemView.findViewById(R.id.school);
                                TextView content = (TextView) itemView.findViewById(R.id.content);
                                Glide.with(getActivity()).load(AppConstants.IMG_URL + model.getTeacher().getRecimg()).diskCacheStrategy(DiskCacheStrategy.ALL
                                ).error(R.mipmap.ls).transform(new GlideRoundTransform(getActivity(), 10)).into(img);
                                name.setText(model.getName() + "/");
                                school.setText(model.getSchool());
                                if (!StringUtils.isEmpty(model.getTeacher().getRecintro())) {
                                    content.setText(model.getTeacher().getRecintro());
                                } else {
                                    content.setVisibility(View.GONE);
                                }


                            }

                        });

//                        Banner2.setData(teacherBeanXes, null);
                        headlinesBean = index.getHeadlines();
                        orderBean = index.getOrder();
                        if (headlinesBean != null) {
                            Glide.with(getActivity())
                                    .load(AppConstants.IMG_URL + headlinesBean.getImg())
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .error(R.mipmap.iv_err)
                                    .into(imageView);
                            tvNew.setText(headlinesBean.getName());

                        }
                        if (orderBean != null) {
                            Glide.with(getActivity())
                                    .load(AppConstants.IMG_URL + orderBean.getImg())
                                    .asBitmap()
                                    .error(R.mipmap.iv_err)
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .into(ivMf);

                        }
                        LoadDialog.closeDialog();
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        Toast.makeText(getActivity(), "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                        LoadDialog.closeDialog();
                    }
                });
        tvNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HeadlinesActivity.class));
            }
        });


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onRefresh() {
        getValue();
    }


    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            // Toast.makeText(this,sdDir.toString(),Toast.LENGTH_LONG).show();
            return sdDir.toString();
        } else {
            Toast.makeText(getActivity(), "没有SD卡", Toast.LENGTH_LONG).show();
        }

        return null;
    }
}
